﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AlarmManagePlatform.UC
{
    public partial class TaskManagement : UserControl
    {
        public TaskManagement()
        {
            InitializeComponent();

            InitControls();

            btnSearch_Click(null,new EventArgs());
        }

        private void InitControls()
        {
            dateBegin.Value = DateTime.Now.AddDays(-1);
            dateFinish.Value = DateTime.Now;
            InitComBoxUserInfo();

            pagTask.Event_SearchDataInfo += PagTask_Event_SearchDataInfo;
            pagTask.Event_UpdatePagingControl += btnSearch_Click;

            Static.Methods.CreateDGVColumns(ref dgvTaskInfo, Model.SystemEnum.DGVType.TaskInfo);
            dgvTaskInfo.CellClick += DgvTaskInfo_CellClick;

            Static.Methods.CreateDGVColumns(ref dgvAlarmSimple,Model.SystemEnum.DGVType.AlarmSimpleType);
            dgvAlarmSimple.Columns["Selected"].Visible = false;
            dgvAlarmSimple.Columns["Delete"].Visible = false;
        }

        private void PagTask_Event_SearchDataInfo(int pageIndex, int pageSize)
        {
            int _StartIndex = (pageIndex * pageSize) + 1;
            int _SearchCount = pageSize;

            Dictionary<string, string> _LogisticList = GetLogisticList();
            List<Model.DB.tb_TaskInfo> _ListInstrument = new DataAccess.tb_TaskInfo().GetTaskList(_StartIndex, _SearchCount, _LogisticList);
            dgvTaskInfo.DataSource = _ListInstrument;


            if (dgvTaskInfo.SelectedRows.Count <= 0 && dgvTaskInfo.Rows.Count > 0)
            {
                dgvTaskInfo.Rows[0].Selected = true;
            }

            if (dgvTaskInfo.SelectedRows.Count > 0)
                DgvTaskInfo_CellClick(null, new DataGridViewCellEventArgs(0, dgvTaskInfo.SelectedRows[0].Index));
            else
            {
                dgvAlarmSimple.DataSource = null;
            }
        }

        private void InitComBoxUserInfo()
        {
            Static.Methods.InitComBox(ref cmbUser, Model.SystemEnum.ComBoxType.UserInfo);
        }

        private void DgvTaskInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            dgvAlarmSimple.DataSource = null;
            List<Model.DB.tb_TaskDetails> _ListTaskDeatil = new DataAccess.tb_TaskDetails().get(dgvTaskInfo.SelectedRows[0].Cells["Id"].Value.ToString());

            List<Model.DB.tb_AlarminstrumentInfo> _ListAlarmInstrumentInfo = new DataAccess.tb_AlarminstrumentInfo().GetInstrumentForFactoryNumberMore(_ListTaskDeatil.Select(x=>x.FactoryNumber).ToList());
            dgvAlarmSimple.DataSource = _ListAlarmInstrumentInfo;

            if (sender != null && e.RowIndex >= 0)
            {
                if (dgvTaskInfo.Rows[e.RowIndex].Cells["Selected"].Value != null && (bool)dgvTaskInfo.Rows[e.RowIndex].Cells["Selected"].Value)
                    dgvTaskInfo.Rows[e.RowIndex].Cells["Selected"].Value = false;
                else
                    dgvTaskInfo.Rows[e.RowIndex].Cells["Selected"].Value = true;
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Forms.TaskForm taskForm = new Forms.TaskForm();
            
            if (taskForm.ShowDialog() == DialogResult.OK)
            {
                Static.ParaInfo.TaskCumulativeNumber++;
                taskForm.TaskInfo.CreateTime = DateTime.Now.ToString(Static.ParaInfo.DateFormatLong);
                taskForm.TaskInfo.Status = 1;

                try
                {
                    new DataAccess.tb_TaskInfo().AddTaskInfo(taskForm.TaskInfo);
                    btnSearch_Click(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("添加数据失败："+ ex.ToString());
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            dgvTaskInfo.DataSource = null;

            Dictionary<string, string> _LogisticList = GetLogisticList();

            int _DataCount = new DataAccess.tb_TaskInfo().GetInfoCount(_LogisticList);

            pagTask.IniEnabled(_DataCount);

            //List<Model.DB.tb_TaskInfo> _ListTaskInfos = new DataAccess.tb_TaskInfo().GetAllInfo();
            //dgvTaskInfo.DataSource = _ListTaskInfos;

            //if (dgvTaskInfo.SelectedRows.Count <= 0 && dgvTaskInfo.Rows.Count > 0)
            //{
            //    dgvTaskInfo.Rows[0].Selected = true;
            //}

            //if (dgvTaskInfo.SelectedRows.Count > 0)
            //    DgvTaskInfo_CellClick(null, new DataGridViewCellEventArgs(0, dgvTaskInfo.SelectedRows[0].Index));
            //else
            //{
            //    dgvAlarmSimple.DataSource = null;
            //}
        }

        private Dictionary<string, string> GetLogisticList()
        {
            Dictionary<string, string> _Result = new Dictionary<string, string>();

            if (checkDatetime.Checked)
            {
                _Result.Add("BeginTime", dateBegin.Value.ToString(Static.ParaInfo.DateFormatShort + " 00:00:00"));
                _Result.Add("FinishTime", dateFinish.Value.ToString(Static.ParaInfo.DateFormatShort + " 23:59:59"));
            }
            else
            {
                _Result.Add("BeginTime", string.Empty);
                _Result.Add("FinishTime", string.Empty);
            }

            _Result.Add("TaskNumber", checkTaskNumber.Checked ? txtTaskNumber.Text : string.Empty);

            _Result.Add("UserId", checkUser.Checked ? cmbUser.SelectedValue.ToString() : string.Empty);

            return _Result;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            List<string> _IndexList = new List<string>();
            bool _Select;
            for (int i = 0; i < dgvTaskInfo.Rows.Count; i++)
            {
                if (dgvTaskInfo.Rows[i].Cells["Selected"].Value == null) continue;
                _Select = (bool)dgvTaskInfo.Rows[i].Cells["Selected"].Value;
                if (_Select)
                    _IndexList.Add(dgvTaskInfo.Rows[i].Cells["Id"].Value.ToString());
            }

            if (_IndexList.Count <= 0)
            {
                MessageBox.Show(this, "请选择任务信息！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (MessageBox.Show("是否确认删除？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                try
                {
                    //由简单到深删除
                    //tb_TaskDetails
                    new DataAccess.tb_TaskDetails().DeleteForTaskID(_IndexList);
                    //tb_TaskInfo
                    new DataAccess.tb_TaskInfo().DeleteForTaskID(_IndexList);
                    btnSearch_Click(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "删除任务数据失败，错误信息：" + ex.Message, "异常信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            if (dgvTaskInfo.SelectedRows.Count <= 0)
            {
                MessageBox.Show(this, "请选择任务信息！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (dgvTaskInfo.SelectedRows[0].Cells["Status"].Value.ToString() != "1")
            {
                MessageBox.Show(this, "任务进行中或已完成，无法进行修改！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }


            Model.DB.tb_TaskInfo _Temp = new DataAccess.tb_TaskInfo().GetInfoForId(dgvTaskInfo.SelectedRows[0].Cells["Id"].Value.ToString());

            if (_Temp == null)
            {
                MessageBox.Show(this, "任务Id下无相关信息！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            _Temp.TaskDetails = new DataAccess.tb_TaskDetails().get(_Temp.Id);

            Forms.TaskForm _TaskForm = new Forms.TaskForm();
            _TaskForm.ModifyInfo(_Temp);

            if (_TaskForm.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    _TaskForm.TaskInfo.Id = _Temp.Id;
                    new DataAccess.tb_TaskInfo().UpdateTaskInfo(_TaskForm.TaskInfo);

                    btnSearch_Click(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("修改任务失败，错误信息：" + ex.ToString());
                }
            }
        }
    }
}
